package com.shakev.coupon.web.controller;

import com.shakev.coupon.es.model.IdListDto;
import com.shakev.coupon.es.model.Mark;
import com.shakev.coupon.es.service.EGoodsDetailService;
import com.shakev.coupon.es.service.EMarkService;
import com.shakev.coupon.taobao.model.GoodsDetail;
import com.shakev.coupon.web.model.base.RestResponse;
import lombok.Data;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @ClassName MarkController
 * @Description TODO
 * @Author 李伟松
 * @CreateDate 2019-06-12 下午 11:09
 * @UpdateDate 2019-06-12 下午 11:09
 * @Version 1.0
 */
@RestController
public class MarkController {

    @Resource
    EMarkService markService;

    @Resource
    EGoodsDetailService goodsDetailService;

    @PostMapping("/mark/add")
    public RestResponse add(@RequestBody Mark mark ) {
        mark.setUserId("1");
        Mark res = markService.findByMark(mark);
        if (res == null) {
            Mark result = markService.save(mark);
            if (result != null) {
                return RestResponse.success();
            }
        }
        return RestResponse.failure("收藏失败");
    }

    @PostMapping("/mark/delete")
    public RestResponse delete(@RequestBody IdListDto param) {
        List<String> itemIds = param.getItemIds();
        for (String itemId : itemIds) {
            Mark mark = new Mark();
            mark.setUserId("1");
            mark.setItemId(itemId);
            markService.delete(mark);
        }
        return RestResponse.success();
    }

    @GetMapping("/mark/list")
    public RestResponse list(Integer pageNo, Integer pageSize) {
        List<String> list = markService.queryItemIdsByUserId(pageNo,pageSize,"1");
        if (list != null && list.size() > 0) {
            String[] itemIds = new String[list.size()];
            list.toArray(itemIds);

            Map<Long,GoodsDetail> map = goodsDetailService.queryMapByItemids( itemIds);

            List<GoodsDetail> res = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                res.add(map.get(Long.parseLong(list.get(i))));
            }

            if (res != null) {
                return RestResponse.success(res);
            }
        }
        return RestResponse.success();

    }
}
